package ltd.followkba.comment;


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.net.ssl.HttpsURLConnection;

import ltd.advskin.utils.SubUtils;
import ltd.advskin.utils.SysUtils;
import ltd.followkba.comment.bean.BTaskRun;
import ltd.followkba.comment.bean.BUserInfo;
import ltd.followkba.comment.utils.CodeBase64;
import main.MAPI;

import static ltd.advskin.MSKIN.MSTRING;
import static ltd.followkba.comment.MKCC.APPC_MODIFY_ACCOUNTID;
import static ltd.followkba.comment.MKCC.APPC_WEIBO_AUTH;
import static ltd.followkba.comment.MKCC.APPC_WEIBO_REGISTER;

public class RegisteChangBa extends TransChangBa {
    private int gSucessQty;
    private boolean isFindLocation;
    public String weibo_token;
    public String weibo_uid;
    public String mAccountID;
    public String mPassword;
    private String gsRegisterChnagBaDbs;
    public String gsRegChangBa;

    public RegisteChangBa(){
//        gSucessQty =
        gsRegisterChnagBaDbs = gsWorkPath + "register.dbs";
        gsRegChangBa = gsWorkPath + "RegChangBa.lst";
//        MSTRING("gsWorkPath "+gsWorkPath);
    }


    public void RegisterAccount(){
        Runnable runnable = new Runnable() {
            public void run() {
                MSTRING("开始注册唱吧");
                String gsLocal_1 = MBAPP.RD_PRIVATE_STRING("weiboRx", MBAPP.gsMainMem);
                String[] params = SplitWeiBoAcount(gsLocal_1);
                if (params != null) {
                    MSTRING("ddd 1"+gsLocal_1);
                    BUserInfo aUserInfo = GetNewChangBaUser();
                    int g4Local_1 = MBAPP.RD_PRIVATE_VALUE("regcity", MBAPP.gsMainMem);
                    MBAPP.WR_PRIVATE_VALUE("regcity", g4Local_1+1, MBAPP.gsMainMem);
                    gsLocal_1 = MUTIL.GET_CITY_LOCAL(g4Local_1);
                    MSTRING("ddd 2"+gsLocal_1);
                    String[] citys = gsLocal_1.split(" ");;
                    if (citys !=null && citys.length > 3) {
                        aUserInfo.province = citys[0].replace(" ", "");
                        aUserInfo.city = citys[1].replace(" ", "");
                        aUserInfo.longitude = citys[2].replace(" ", "");
                        aUserInfo.latitude = citys[3].replace(" ", "");
                    }
                    MSTRING("ddd 3"+aUserInfo.province+" "+aUserInfo.city+" "+aUserInfo.longitude+" "+aUserInfo.latitude+" "+aUserInfo.intro);
                    if (aUserInfo != null) {
                        MSTRING(String.format("准备唱吧：%s(%s)%s(%s)%s",aUserInfo.nickName,aUserInfo.userID,aUserInfo.intro,aUserInfo.songQty,aUserInfo.headUrl));
                        gsLocal_1 = WeiBoAuthChangBa(params[0], params[1]);
                        //transChangBa.mChangBa.mUserID="113211234";transChangBa.mChangBa.mToken="Tda0047851f41123";
                        if ("ok".equals(gsLocal_1)){
                            MSTRING(String.format("aaa %s %s %s %s", gsUserID, gsToken, aUserInfo.userID, aUserInfo.gender));
                            String gsLocal_3 = ModifyUseInfo(5, aUserInfo);
                            String gsLocal_4 = uploadPhotoFile(aUserInfo.headUrl, "", null);
                            BTaskRun bTaskRun = new BTaskRun();
                            String gsLocal_5 = copyMediaFile(0, -1, aUserInfo, bTaskRun, "");
                            byte gpLocal_1[] = MUTIL.USERID_TOKEN_BUFF8(gsUserID, gsToken, "");
                            byte gpLocal_2[] = new byte[32];
//                            MAPI.COPY_BUFF8(gpLocal_1.length, 0, gpLocal_1, 0, gpLocal_2);
                            MAPI.COPY_BYTES(gpLocal_2, 0, gpLocal_1, 0, gpLocal_1.length);
                            MAPI.WRITE_BUFF8_FILE(true, gpLocal_2.length, 0, gpLocal_2, gsRegisterChnagBaDbs);
                            String gsLocal_6 = CodeBase64.encodeBytes(gpLocal_1);
                            String gsLocal_7 = mAccountID + "----" + mPassword + "----" + aUserInfo.gender + gsLocal_6;
                            g4Local_1 = MBAPP.RD_PRIVATE_VALUE("length", gsRegChangBa);
                            MBAPP.WR_PRIVATE_VALUE("length", g4Local_1+1, gsRegChangBa);;
                            MBAPP.WR_PRIVATE_STRING(g4Local_1, gsLocal_7, gsRegChangBa);
                            g4Local_1 = (int) MAPI.GET_FILE_LENGTH(gsRegisterChnagBaDbs) / 32;
                            MSTRING(String.format("%d注册唱吧：%s 信息 %s 头像 %s 文件 %s",g4Local_1, gsLocal_7, gsLocal_3, gsLocal_4, gsLocal_5));
                            CHANGBA_PUT_FLOWER();
                            gsLocal_1 = "1" + params[0] +"&"+ params[1] +"#B"+ gsLocal_7;
                            MBAPP.WR_PRIVATE_STRING("weiboTx", gsLocal_1, MBAPP.gsMainMem);
                            MBAPP.WR_PRIVATE_STRING("weiboRx", "", MBAPP.gsMainMem);
                            MKCS.FSinaWeiboTx = true;
                        }
                        else {
                            gsLocal_1 = "1" + params[0] +"&"+ params[1] +"#0"+ gsLocal_1;
                            MBAPP.WR_PRIVATE_STRING("weiboTx", gsLocal_1, MBAPP.gsMainMem);
                            MBAPP.WR_PRIVATE_STRING("weiboRx", "", MBAPP.gsMainMem);
                            MKCS.FSinaWeiboTx = true;
                        }
                    }
                    else {
                        MSTRING("可能是网络的问题，等会再试下");
                        MKCS.gSinaWeiboRx = 1;                   // 可能是网络的问题，等会再试下
                    }
                }
                if (MKCS.gSinaWeiboRx == 2) {
                    MKCS.gSinaWeiboRx = 0;
                }
                MSTRING("唱吧完成，线程退出");
            }
        };
        Thread thread = new Thread(runnable);
        thread.start();
    }


    public BUserInfo GetNewChangBaUser(){
        BUserInfo userInfoChangeBa;
        BUserInfo userInfoYanChange;
        KgYanChang kgYanChang = new KgYanChang();
        int g4Local_1 = 0;
        int g4Local_2;
//MDWORD(0x88);
        do {
            userInfoYanChange = kgYanChang.GetValidUseInfo(-1);
            if (userInfoYanChange != null && !"".equals(userInfoYanChange.nickName)){
                g4Local_2 = 0;
                do {
                    userInfoChangeBa = GetValidUseInfo(-1);
//MDWORD(0x99);MDWORD(g4Local_1);MLOG(userInfoChangeBa);
                    if (userInfoChangeBa != null && userInfoChangeBa.songQty > 2){
                        MSTRING(userInfoYanChange +" "+userInfoYanChange);
                        userInfoYanChange.nickName = userInfoYanChange.nickName.replace("@", "");
                        userInfoChangeBa.nickName = userInfoYanChange.nickName;
                        userInfoChangeBa.headUrl = userInfoYanChange.headUrl;
                        if (!"".equals(userInfoYanChange.intro)) {
                            userInfoChangeBa.intro = userInfoYanChange.intro;
                        }
                        userInfoChangeBa.province = userInfoYanChange.province;
                        userInfoChangeBa.city = userInfoYanChange.city;
                        userInfoChangeBa.longitude = userInfoYanChange.longitude;
                        userInfoChangeBa.latitude = userInfoYanChange.latitude;
//MLOG(55555);MLOG(userInfoYanChange.HeadUrl);
                        return userInfoChangeBa;
                    }
                } while (++g4Local_2 < 50);
            }
        } while (++g4Local_1 < 50);
        return null;
    }
    private String[] SplitWeiBoAcount(String gsLocal_1){
        String[] params = gsLocal_1.split("&");
        if (params.length > 1){
            if (params[0].startsWith("1")) {
                params[0] = gsLocal_1.substring(1, params[0].length());
                return params;
            }
        }
        return null;
    }
    public String WeiBoAuthChangBa(String account, String password){
//        account="tanghei67lanpo@163.com";password="Wy19N6T31A";

        String gsLocal_1 = "";
        String gsLocal_2 = "";
        weibo_token = "";
        weibo_uid = "";
        try {
            gsLocal_1 = Authorize(account, password);
            MSTRING(account+" " +password+" " +gsLocal_1+" " +weibo_token+" " +weibo_uid);
            if (gsLocal_1.indexOf("错") >= 0){
                return gsLocal_1;
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
//weibo_token="2.00lZiFZGPqdB_B6f7c5b09c6LqdsYB";weibo_uid="6015331745";
//weibo_token = "2.00IhFVaGPqdB_B2df493b83f2RLHOC"; weibo_uid = "6036155150";
        int g4Local_1;
        if ("".equals(weibo_token) || "".equals(weibo_uid)){
            return "新浪授权不成功";
        }
        ResultNet resultNet = null;
        g4Local_1 = 0;
        gsLocal_1 = "";
        SubUtils sysUtils = new SubUtils();
        do {
            if ((g4Local_1 & 0x01) > 0){
                gsLocal_2 = sysUtils.readAndRemoveTextLine(MKCS.gsChangBaSsid);
                String[] params = gsLocal_2.split("#");
                if (params.length > 1) {
                    gsLocal_1 = params[0];
                    gsLocal_2 = params[1];
                }
                if ((g4Local_1 & 0x02) > 0){
                    if (gsLocal_1.startsWith("c2")){
                        gsLocal_2 = "";
                    }
                }
                MSTRING("唱吧授权验证码："+gsLocal_1 + " " + gsLocal_2);
            }
            else {
                gsLocal_1 = "";
                gsLocal_2 = "";
            }
            resultNet = WriteCommand(APPC_WEIBO_AUTH, weibo_token, gsLocal_1, gsLocal_2);
            if (resultNet.sucess) {             //
                break;
            }
            else if (resultNet.message.indexOf("账号") >= 0){                   // 你的账号似乎有些异常,被锁定登陆。请发送jcsd到106900802376或联系唱吧客服解除锁定
                return "唱吧帐号出错："+resultNet.message;
            }
            else if (resultNet.message.indexOf("网络请求") >= 0){                  // 你的网络请求似乎过于频繁，请稍后重试，或者联系唱吧客服
                MSTRING("注意：" + resultNet.message);
                DELAY_RANDOM_SECOND(60 * 60 * 2);           // 2小时
            }
            DELAY_RANDOM_SECOND(20);
        } while (++g4Local_1 < 15);
        if (resultNet == null || !resultNet.sucess) {
            return "唱吧注册或者登录不成功：" + resultNet.message;
        }
        gsLocal_1 = MUTIL.GET_JSON_STRING(resultNet.nextJason, "stat");
        if ("register".equals(gsLocal_1)) {
            MSTRING("唱吧注册");
            g4Local_1 = 0;
            do {
                resultNet = WriteCommand(APPC_WEIBO_REGISTER, weibo_token, weibo_uid, "");
                if (resultNet.sucess){
                    break;
                }
            } while (++g4Local_1 < 10);
            gsLocal_1 = resultNet.nextJason;
        }
        else if ("login".equals(gsLocal_1)) {
            gsLocal_1 =  MUTIL.GET_JSON_STRING(resultNet.nextJason, "userdata");
        }
        String accountID =  MUTIL.GET_JSON_STRING(gsLocal_1, "accountid");
        gsUserID =  MUTIL.GET_JSON_STRING(gsLocal_1, "userid");
        gsToken =  MUTIL.GET_JSON_STRING(gsLocal_1, "token");
        MSTRING("WeiBoAuthChangBa &accountid="+accountID+"&userid="+gsUserID+"&token="+gsToken);
        if ("".equals(gsUserID) || "".equals(gsToken)){
            return "唱吧登录出错";
        }
        mAccountID = accountID;
        if ("".equals(accountID)){
            g4Local_1 = account.indexOf('@');
            if (g4Local_1 > 0) {
                accountID = account.substring(0, g4Local_1);
            }
            else {
                accountID = "a" + accountID;
            }
//            accountID = account.substring(0, g4Local_1);
            password = password.toLowerCase();
            //   account="jzpwengxntao@163.com";password="w7b8CM9";
//password="cc12345678";
            //   String AudioUrl = "https://secure.changba.com/ktvboxs.php?ac=iinituseraccountid&token="+token+"&curuserid="+UserIdS+"&password=" + MUTIL.GET_MD5_STRING(password) + "&accountid=";
//MDWORD(0xb2);MLOG(accountID);MLOG(password);
            g4Local_1 = 0;
            do {
                resultNet = WriteCommand(APPC_MODIFY_ACCOUNTID, accountID, password, "");
                if (resultNet.sucess){
                    mAccountID = accountID;
                    mPassword = password;
                    MSTRING("WeiBoAuthChangBa ok "+accountID+"&password="+mPassword+"&userid="+gsUserID+"&token="+gsToken);
                    return "ok";
                }
                accountID += g4Local_1 + "1";
            } while (++g4Local_1 < 10);
            return "修改唱吧号出错";
        }
        return "ok";
    }
    public String Authorize(String ac, String pw) throws UnsupportedEncodingException {
        weibo_token = "";
        weibo_uid = "";
        String referer_1 = "https://passport.weibo.cn/signin/login?client_id=1197274699&redirect_uri=http://changba.com/login_success.html&display=sdk&action=login&offcialMobile=true&rf=1&version=0031205000&sso_type=1&scope=email,direct_messages_read,direct_messages_write,friendships_groups_read,friendships_groups_write,statuses_to_me_read";
        String path_1 = "https://passport.weibo.cn/sso/login";
        String content_1 = "username="+ URLEncoder.encode(ac,"utf-8")+"&password="+pw+"&savestate=1&ec=0&pagerefer=&entry=mweibo&wentry=&rf=1&loginfrom=2&client_id=1197274699&code=&qq=&hff=&hfp=";
        String str_re = httpsConnectionPost(path_1,content_1,referer_1);
        if (MUTIL.GET_JSON_VALUE(str_re, "retcode") != 20000000){
            return "新浪出错1：" + MUTIL.GET_JSON_STRING(str_re, "msg");
        }
        String data = MUTIL.GET_JSON_STRING(str_re, "data");
        String ticket = MUTIL.GET_JSON_STRING(data, "ticket");
        weibo_uid = MUTIL.GET_JSON_STRING(str_re, "uid");
        MSTRING("返回1="+str_re);
        MSTRING("从1找到ticket="+ticket);
//        System.out.println(ticket);
        String path_2 = "https://open.weibo.cn/oauth2/authorize";
        String content_2 = "client_id=1197274699&redirect_uri=http%3A%2F%2Fchangba.com%2Flogin_success.html&display=sdk&action=login&offcialMobile=true&rf=1&version=0031205000&sso_type=1&scope=email%2Cdirect_messages_read%2Cdirect_messages_write%2Cfriendships_groups_read%2Cfriendships_groups_write%2Cstatuses_to_me_read&wm=3349&ticket="+ticket;
        isFindLocation = false;
        String str_re_2 = httpsConnectionPost(path_2,content_2,referer_1);
        if (!isFindLocation) {
            MSTRING("没有返回2之中找到location，重新在线正则匹配的网址：" + str_re_2);
            Pattern pattern = Pattern.compile("<input type=\"hidden\".*?name=\"(.*?)\".*?value=\"(.*?)\"/>");
            Matcher matcher = pattern.matcher(str_re_2);
            StringBuilder builder = new StringBuilder();
            while (matcher.find()) {
                builder.append(matcher.group(1) + "=" + matcher.group(2) + "&");
                System.out.println(matcher.group(1) + "--" + matcher.group(2));
            }
            String referer_3 = "https://open.weibo.cn/oauth2/authorize";
            String content_3 = "";
            if (builder.toString().length() > 0) {
                content_3 = builder.toString().substring(0, builder.length() - 1);
            }
            String path_3 = "https://open.weibo.cn/oauth2/authorize";
            String str_re_3 = httpsConnectionPost(path_3, content_3, referer_3);
            MSTRING("返回3="+str_re_3);
            MSTRING("从3找到weibo_token = "+weibo_token +" weibo_uid = "+weibo_uid);
        }
        else {
            MSTRING("从2找到weibo_token = "+weibo_token +" weibo_uid = "+weibo_uid);
        }
        if ("".equals(weibo_token) || "".equals(weibo_uid)){
            return "新浪出错2：没有找到token或uid，可能需要验证码";
        }
        return "";
    }
    private String httpsConnectionPost(String path, String content, String refer){
        System.out.println("AudioUrl："+path);
        System.out.println("referer："+refer);
        System.out.println("content："+content);
        String re = null;
        try {
            URL url = new URL(path);
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("User-Agent","Mozilla/5.0 (Linux; Android 5.1.1; Redmi 3 Build/LMY47V; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/45.0.2454.95 Mobile Safari/537.36");
            connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
            connection.setRequestProperty("Referer",refer);
            connection.connect();
            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(content.getBytes());
            outputStream.close();
            StringBuilder builder = new StringBuilder();
            String line;
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"utf-8"));
            while((line = reader.readLine())!=null){
                builder.append(line);
            }
            reader.close();
            String location = connection.getHeaderField("Location");
            if (location!=null){
                isFindLocation = location.startsWith("http://changba.com/login_success.html");
                if (isFindLocation){
                    weibo_token = location.substring(location.indexOf("access_token=")+13,location.indexOf("&remind"));
                    weibo_uid = location.substring(location.indexOf("uid=")+4,location.length());
                }
                System.out.println("Location：" + location);
            }
            connection.disconnect();
            //           System.out.println("return："+builder.toString());
            re = builder.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return re;
    }
    private void CHANGBA_PUT_FLOWER(){
        int g4Local_1 = 0;
        int g4Local_2 = 3;
        int g4Local_3;
        String gsLocal_1;
        String gsLocal_2;
        BUserInfo aUserInfo;
        do {
            g4Local_3 = GetUserFromRank();
            aUserInfo = GetUserFullInfo(String.format("%d", g4Local_3));
            if (aUserInfo != null) {
//MLOG(gsLocal_6);MLOG(aUserInfo.UserName);MLOG(aUserInfo.WorksQty);MLOG(aUserInfo.IdS.get(0));
                //                             resultNet = transChangBa.mChangBa.WriteCommand(APPC_PUT_FLOWER, "789793580", "", "");
                if (g4Local_2 > 0) {
                    g4Local_2 = MAPI.STRING_DEC32(PutFlowerToSong(aUserInfo.songIDs.get(0)));
                }
                gsLocal_1 = MUTIL.GET_AUTO_COMMENT();
                gsLocal_2 = PutCommentToSong(aUserInfo.userID, aUserInfo.songIDs.get(0), "", gsLocal_1);
                gsLocal_1 = String.format("唱吧%d送花(%d) %s(%s)->%s 评论(%s)%s", g4Local_1, g4Local_2, aUserInfo.nickName, aUserInfo.userID, aUserInfo.songIDs.get(0), gsLocal_2, gsLocal_1);
                MSTRING(gsLocal_1);
            }
            DELAY_RANDOM_SECOND(20);
        } while(++g4Local_1 < 10);
    }
    public void DELAY_RANDOM_SECOND(int second) {
        second = second * 1000;
        Random random = new Random();
        int g4Random = Math.abs(random.nextInt()) % second;
        MAPI.MSLEEP((second / 2) + g4Random);
    }

}
